﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Swoosh.Contracts.MediaPlayerLib;
using System.Xml.Serialization;
using System.IO;
using Swoosh.Utilities.TraceLogger;
using System.Net;

namespace Swoosh.MediaPlayers.XbmcDharma
{
    public class Player : IPlaybackDevice
    {

        private string _Name;
        public string Name
        {
            get { return _Name; }
            set { _Name = value; }
        }

        private string _StorageName;
        public string StorageName
        {
            get { return _StorageName; }
            set { _StorageName = value; }
        }

        public Storage Storage
        {
            get
            {
                return SwooshConfig.CurrentConfig.StorageList.Where(s => s.Name == StorageName).FirstOrDefault();
            }
        }

        private Playlist _Playlist;
        public Playlist Playlist
        {
            get { return _Playlist; }
        }

        private XbmcDharmaConfig _Config;

        public Player()
        {
            _Name = "";
            _StorageName = "";
            _Playlist = new Playlist();
        }

        private string SendCommand(string postData)
        {
            string requesturi = "http://" + _Config.ServerName + ":" + _Config.ServerPort + "/JSONRPC";

            WebRequest web_request = WebRequest.Create(requesturi);

            UTF8Encoding encoding = new UTF8Encoding();
            Logger.Log(LogLevels.Debug, postData);
            byte[] data = encoding.GetBytes(postData);

            // Prepare web request...
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requesturi);
            request.Method = "POST";
            request.ContentType = "application/json";
            request.ContentLength = data.Length;
            Stream newStream = request.GetRequestStream();
            // Send the data.
            newStream.Write(data, 0, data.Length);
            newStream.Close();

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream res = response.GetResponseStream();
            StreamReader reader = new StreamReader(res);
            string ret = reader.ReadToEnd();
            
            Logger.Log(LogLevels.Debug, ret);

            return ret;
        }

        public bool ClearPlaylist()
        {
            string postData = "{\"method\":\"VideoPlaylist.Clear\",\"id\" : 0,\"jsonrpc\" : \"2.0\"}";
            SendCommand(postData);
            return true;
        }

        public bool QueuePlaylistItem(PlaylistItem Item)
        {
            string postData = "{\"method\":\"VideoPlaylist.Add\",\"params\":{\"file\":\"" + Item.File.Replace("\\", "//").Replace("//", "\\\\") + "\"}, \"id\" : 0,\"jsonrpc\" : \"2.0\"}";
            SendCommand(postData);
            return true;
        }

        public bool StopPlayback()
        {
            string postData = "{\"method\":\"VideoPlayer.Stop\", \"id\" : 0,\"jsonrpc\" : \"2.0\"}";
            SendCommand(postData);
            return true;
        }

        public bool PlayPlaylistItem(PlaylistItem Item)
        {
            string postData = "{\"method\":\"VideoPlaylist.Play\",\"params\":" + Item.Position + ", \"id\" : 0,\"jsonrpc\" : \"2.0\"}";
            SendCommand(postData);
            
            SeekInCurrentPlayback(Item);
            
            return true;
        }

        private bool SeekInCurrentPlayback(PlaylistItem Item)
        {
            string postData = "{\"method\":\"VideoPlayer.SeekTime\",\"params\":" + Item.SeekTime + ", \"id\" : 0,\"jsonrpc\" : \"2.0\"}";
            SendCommand(postData);
            return true;
        }

        public Playlist ReadPlayList()
        {
            _Playlist = new Playlist();

            string postData = "{\"method\":\"VideoPlaylist.GetItems\", \"id\" : 0,\"jsonrpc\" : \"2.0\"}";
            string retData = SendCommand(postData);

            //JObject jobj = JObject.Parse(retData);

            //Logger.Log(LogLevels.Debug, "paused: " + jobj["result"]["paused"].Value<bool>().ToString());

            return _Playlist;
        }

        public bool LoadConfiguration(string Configuration)
        {
            bool ret = false;

            XmlSerializer xmlSer = new XmlSerializer(typeof(XbmcDharmaConfig));

            try
            {
                _Config = (XbmcDharmaConfig)xmlSer.Deserialize(new StringReader(Configuration));

                ret = true;
            }
            catch (Exception ex)
            {
                Logger.Log(LogLevels.Error, Name + " - unable to load configuration", ex);
                _Config = new XbmcDharmaConfig();
            }
            return ret;
        }

        public bool Start()
        {
            return true;
        }

        public bool Stop()
        {
            return true;
        }
    }
}
